(function () {
  'use strict';

  angular.module('BlurAdmin.theme.components')
      .controller('AgoraVideoCtrl', AgoraVideoCtrl);

  /** @ngInject */
  function AgoraVideoCtrl($scope, AVService, videoStatus, $window, alertService, $state, $uibModal, Fullscreen) {
    $scope.streams = videoStatus.streams;
    $scope.liveShow = videoStatus.live;

    var teacherUid = $scope.channel.substring(0,8);
    teacherUid = teacherUid.split('');
    for (var i = 0; i < teacherUid.length; i++) {
      if (isNaN(teacherUid[i])) {
        teacherUid[i] = teacherUid[i].charCodeAt(0) % 10;
      }
    }
    teacherUid = teacherUid.join("");
    teacherUid = parseInt(teacherUid);
    console.log(teacherUid);

    
    var localStream, lastLocalStreamId;
    var client = videoStatus.client;
    console.log(videoStatus);

    if (!client) {
      client = AgoraRTC.createRtcClient();
      console.log(client)
    }

    if (videoStatus.live !== true) {
      client.init($scope.appId, function(obj) {
        console.log("AgoraRTC client initialized");
        client.getDevices (function(devices) {
          var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'app/pages/classManage/syllabus/syllabusMainPage/modal/setVideoProfile.html',
            controller: 'SetVideoProfileModalCtrl',
            resolve: {
              devices: function () {
                return devices;
              },
            }
          });
          modalInstance.result.then(function (modalItem) {
            console.log('select video profile is: ', modalItem.videoProfile);
            console.log('select device is: ', modalItem.videoDevice, modalItem.audioDevice);
            $scope.videoProfile = modalItem.videoProfile;
            client.selectDevice(modalItem.audioDevice);
            client.selectDevice(modalItem.videoDevice);
            if ($scope.cummunicaitonMode) {
              client.join($scope.key, $scope.channel, teacherUid, function(uid) {
                console.log("User " + uid + " join channel successfully");
                console.log("Timestamp: " + Date.now());
                localStream = initLocalStream(uid);
                lastLocalStreamId = localStream.getId();
                videoStatus.live = true;
                $scope.liveShow = videoStatus.live;
                videoStatus.client = client;
                $scope.$apply()
              });
            }
            else {
              var profile = 'live-broadcasting';
              var role = 'broadcaster'; //'CLIENT_ROLE_AUDIENCE'
              client.setChannelProfile(profile, function(err) {
                console.log("client sets the channel mode:", profile);
                client.setClientRole(role, null, function(err) {
                  console.log("client sets the user role:", role);
                  client.join($scope.key, $scope.channel, teacherUid, function(uid) {
                    console.log("User " + uid + " join channel successfully");
                    console.log("Timestamp: " + Date.now());
                    localStream = initLocalStream(uid);
                    lastLocalStreamId = localStream.getId();
                    videoStatus.live = true;
                    $scope.liveShow = videoStatus.live;
                    videoStatus.client = client;
                    $scope.$apply()
                  });
                }, function(err) {
                  console.log("client fails to set the user role", err);
                  //error handling
                });
              }, function(err) {
                console.log("client sets channel mode failure", err);
                //error handling
              });
            }
          }, function () {
            $window.location.href = '/#/classManage/syllabus/syllabusMainPage';
            $window.location.reload();
          });
        });
      }, function(err) {
        console.log(err);
        if (err.reason === 'CLOSE_BEFORE_OPEN') {
          alertService.error('您需要安装agora插件并运行才能进行直播。');
          $state.go('admin.classManage.syllabus.syllabusMainPage')
        }
        videoStatus.live = false;
        $scope.liveShow = videoStatus.live;
        videoStatus.streams = [];
        $scope.$apply()
      });
    }

    function initLocalStream(id, callback) {
      var uid = id;
      if (localStream) {
        // local stream exist already
        client.unpublish(localStream, function(err) {
          console.log("Unpublish failed with error: ", err);
        });
        localStream.close();
      }
      // localStream.setVideoProfile(videoProfile);

      localStream = AgoraRTC.createStream({
        streamID: uid,
        audio: true,
        video: true,
        screen: false,
        local: true
      });

      localStream.setVideoProfile($scope.videoProfile);

      localStream.init(function() {
        console.log("Get UserMedia successfully");
        $scope.streams.push(localStream);
        videoStatus.streams = $scope.streams;
        $scope.$apply();
        // localStream.play('myVideo-0');
        client.publish(localStream, function(err) {
          console.log("Timestamp: " + Date.now());
          console.log(err)
          console.log("Publish local stream error: ", err);
        });
        client.on('stream-published');
        if ($scope.needRecord) {
          $scope.startRecord();
        }

      }, function(err) {
        console.log("Local stream init failed: ", err);
      });
      return localStream;
    }

    subscribeStreamEvents();

    function subscribeStreamEvents() {
      client.on('stream-added', function(evt) {
        var stream = evt.stream;
        console.log("New stream added: " + stream.getId());
        console.log("Timestamp: " + Date.now());
        console.log("Subscribe ", stream);
        client.subscribe(stream, function(err) {
          console.log("Subscribe stream failed", err);
        });
      });

      client.on('peer-leave', function(evt) {
        console.log(evt);
        console.log("Peer has left: " + evt.uid);
        console.log($scope.streams);
        console.log("Timestamp: " + Date.now());
        console.log(evt);
        $scope.streams = $scope.streams.filter(function (item) {
          return item.getId() !== evt.uid;
        });
        videoStatus.streams = $scope.streams;
        console.log($scope.streams);
        $scope.$apply();

      });

      client.on('stream-subscribed', function(evt) {
        var stream = evt.stream;
        console.log("Got stream-subscribed event");
        console.log("Timestamp: " + Date.now());
        console.log("Subscribe remote stream successfully: " + stream.getId());
        console.log(evt);
        $scope.streams.push(stream);
        videoStatus.streams = $scope.streams;
        $scope.$apply();

      });

      client.on("stream-removed", function(evt) {
        var stream = evt.stream;
        console.log("Stream removed: " + evt.stream.getId());
        console.log("Timestamp: " + Date.now());
        console.log(evt);
        $scope.streams = $scope.streams.filter(function (item) {
          return item !== stream;
        });
        videoStatus.streams = $scope.streams;
        $scope.$apply();

      });

      // client.on("user-enable-video", function (event) {
      //   var stream = event.stream;
      //   var message = event.msg;
      //   if (message.muted) {
      //     console.log("remote user " + message.uid + " muted video");
      //   } else {
      //     console.log("remote user " + message.uid + " unmuted video");
      //   }
      //   console.log("user-enable-video successfully: " + stream.getId());
      //   console.log(event);
      //   $scope.streams.push(stream);
      //   videoStatus.streams = $scope.streams;
      //   $scope.$apply();
      //
      // })

      client.on('stream-subscribed', function(evt) {
        var stream = evt.stream;
        console.log("Got stream-subscribed event");
        console.log("Timestamp: " + Date.now());
        console.log("Subscribe remote stream successfully: " + stream.getId());
        console.log(evt);
        $scope.streams.push(stream);
        videoStatus.streams = $scope.streams;
        $scope.$apply();

      });

      client.on("peer-mute-audio", function (event) {
        var message = event.msg;
        if (message.muted) {
          console.log("remote user " + message.uid + " muted audio");
        }
        else {
          console.log("remote user " + message.uid + " unmuted audio");
        }
      });

    }



    $scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
      for (var i=0; i<$scope.streams.length; i++) {
        $scope.streams[i].play('myVideo-' + i);
      }
      console.log($scope.streams)
    });


    $scope.dynamicPopover = {
      content: [],
      templateUrl: 'myPopoverTemplate.html',
      title: '选择要共享的程序'
    };
    
    $scope.shareScreen = function () {
      $scope.dynamicPopover.content = [{content:'加载中...'}];
      client.getWindows(function(data) {
        $scope.dynamicPopover.content = [];
        angular.forEach(data, function (item) {
          if ($.trim(item.title) !== '') {
            $scope.dynamicPopover.content.push({dataId: item.windowId, content: window.Base64.decode(item.title)})
          }
        });
        $scope.$apply();
      })
    };

    $scope.startScreenSharing = function (item) {
      client.startScreenSharing(item.dataId, function(e) {
        $scope.isShared = true;
        $scope.myPopClose = false;
        $scope.$apply();
        console.log("startScreenSharingFailure:" + e);
      }, function(e) {
        console.log(e)
      });
    };

    $scope.stopShareScreen = function () {
      client.stopScreenSharing(function(e) {
        $scope.isShared = false;
        $scope.$apply();
        console.log("stopScreenSharingFailure:" + e);
      }, function(e) {
        console.log(e)
      });
    };
    
    $scope.disableAudio = function (stream) {
      stream.disableAudio();
      stream.hasAudio = !stream.hasAudio;
    };

    $scope.enableAudio = function (stream) {
      stream.enableAudio();
      stream.hasAudio = !stream.hasAudio;
    };

    $scope.enableLocalAudio = function () {
      localStream.enableAudio();
    };

    $scope.disableLocalAudio = function () {
      localStream.disableAudio();
    };

    $scope.leave = function () {
      if (client) {
        client.leave();
        videoStatus.streams = [];
        videoStatus.live = false;
        videoStatus.client = undefined;
        $scope.hostLeave = true;
        client = undefined;
        $window.location.href = '/#/classManage/syllabus/syllabusMainPage';
        $window.location.reload();
      }
    };

    $scope.openWhiteBoard = function () {
      $scope.whiteBoardOpened = true;

      // var $scope.key = "74a0b7bb5d3e47c7abca0533d17b0afa",
      //   resolution = "480p",
      //   maxFrameRate = 15,
      //   maxBitRate = 750,
      //   channel = 1234,
      //   client = AgoraRTC.Client({}),
      //   remoteStreamList = [],
      //   localStream;

      var hostParams = {
        key: $scope.key,
        cname: $scope.channel,
        role: 'host',
        width: 1024,
        height: 768,
        container: "whiteBoardContainer"
      };
      /* Call AgoraWhiteBoardApi */
      Agora.Whiteboard.join(hostParams);
    };

    $scope.closeWhiteBoard = function () {
      $scope.whiteBoardOpened = false;
      // angular.element('#whiteBoardContainer').remove();
      // Agora.Whiteboard.leave('http://localhost:3000/#/classManage/syllabus/syllabusMainPage');
      Agora.Whiteboard.leave('/#/classManage/syllabus/syllabusMainPage');
    };
    
    $scope.startRecord = function () {
      if ($scope.recordingKey) {
        console.log('send record command with recordingKey:', $scope.recordingKey);
        client.startRecording($scope.recordingKey, function(data) { 
          console.log("start recording successfully.");
          $scope.isRecording = true;
        }, function(err) {
          console.log("failed to start recording", err);
          $scope.isRecording = false;
        });
      }
      else {
        alertService.error('只有正式系统才能进行录制操作!');
      }
    };

    $scope.stopRecordAndLeave = function () {
      if ($scope.recordingKey) {
        client.stopRecording($scope.recordingKey, function(data) {
          console.log("stop recording successfully.");
          $scope.isRecording = false;
          $scope.leave();
        }, function(err) {
          console.log("failed to stop recording", err);
          $scope.isRecording = true;
        });
      }
      else {
        // alertService.error('只有正式系统才能进行录制操作!');
        $scope.leave();
      }
    };
    
    $scope.FullscreenService = Fullscreen;

    $scope.goFullscreen = function () {
      if (!$scope.isShared) {
        $scope.fullscreenVideoFlag = false;
        $scope.fullscreenAreaFlag = true;
        $scope.fullAreaStreams = [];
        $scope.fullAreaStreams = $scope.streams.slice(0, 4);
        console.log($scope.fullAreaStreams);
        Fullscreen.enable( document.getElementById('videoArea') )
      }
      else {
        Fullscreen.enable( document.getElementById('originVideoArea') )
      }

    };

    $scope.$on('ngRepeatFullVideoFinished', function () {
      for (var i=0; i<$scope.fullAreaStreams.length; i++) {
        $scope.fullAreaStreams[i].play('myAreaVideo-' + i);
      }
    });
    
    $scope.fullscreenVideo = function (id, index) {
      if (!$scope.isShared) {
        $scope.fullscreenAreaFlag = false;
        $scope.fullScreenStreams = [];
        $scope.fullscreenVideoFlag = 'mySigleVideo-0';
        $scope.fullScreenStreams.push($scope.streams[index]);
        if (Fullscreen.isEnabled()) {
          Fullscreen.cancel();
        }
        else {
          Fullscreen.enable( document.getElementById('videoSigleArea') );
        }
      }
      else {
        Fullscreen.enable( document.getElementById('originVideoArea') );
      }

    };

    $scope.$watch('streams', function() {
      $scope.fullAreaStreams = $scope.streams.slice(0, 4);
    });

    $scope.$on('ngIfFinished', function() {
      $scope.fullScreenStreams[0].play($scope.fullscreenVideoFlag)
    });
    

    $scope.cancelFullScreenVideo = function () {
      $scope.fullscreenVideoFlag = undefined;
      $scope.fullscreenAreaFlag = undefined;
      if (Fullscreen.isEnabled()) {
        Fullscreen.cancel();
      }
    };

    Fullscreen.$on('FBFullscreen.change', function(event, isEnabled) {
      if (!$scope.isShared) {
        console.log(event, isEnabled)
        $scope.fullScreenEvent = true;
        setTimeout(function(){ $scope.fullScreenEvent = false }, 500);
        if (!isEnabled) {
          $scope.cancelFullScreenVideo();
        }
      }
    });
    
    






    






  }
})();